define(["jquery","mustache.min","comm","files/flashChecker","site_tip","list_helper","plugin/qtip/jquery.qtip.min",/*"css!/static/js/jquery/jquery-scrollbar/jquery.mCustomScrollbar.css",*/"css!/static/js/jquery/qtip/jquery.qtip.css"],
function($,Mustache,comm,FlashChecker,Site_tip){
    //comm.loadCss("/static/js/jquery/jquery-scrollbar/jquery.mCustomScrollbar.css");
    //comm.loadCss("/static/js/jquery/qtip/jquery.qtip.css");
    var SITE_TIP = new Site_tip();
    var fls= new FlashChecker();
    //整个展示区的容器
    var D_traceList = $("#traceList");
    var D_traceWrap = $("#trace-wrap");
    //文件记录列表容器
    var D_myPage = $("#mypage");
    //文件列表容器
    var D_fileBox = $("#fileBox");
    //日期列表容器
    var D_dateBox = $("#dateBox");
    var D_traceBoxCt = $("#traceBox .ct");

    //文件列表内页
    var D_fileBoxPanel = D_fileBox.find(".panel");
    var D_fileBoxScrollTool = D_fileBox.find(".page-wrap");
    //日期列表内页
    var D_dateBoxPanel = D_dateBox.find(".panel");
    var D_dateBoxScrollTool = D_dateBox.find(".page-wrap");

    var C_dateBoxMinLen=6;

    var P_loadFiles,P_loadTraces;
    function autoAdjustView()
    {
        //计算高度
        /*var height = $(window).height() - parseInt($('.wf_header').height()) -2 - parseInt($('.tool-view').outerHeight(true));
        D_traceList.height(height);*/
        adjustDateBox();
        adjustFileBox();
        //D_myPage.height(height-D_traceBox.find(".list-title").height() - 55 - 43);
    }
    function adjustFileBox()
    {
        if(D_fileBoxPanel.length>0)
        {
            D_fileBoxPanel[0].scrollHeight>D_fileBoxPanel.height()?D_fileBoxScrollTool.show():D_fileBoxScrollTool.hide();
        }
    }
    function adjustDateBox()
    {
        if(D_dateBoxPanel.length>0)
        {
            //console.log("%s %s",D_dateBoxPanel[0].scrollHeight>D_dateBoxPanel.height(),D_dateBoxPanel.find("li.not-data:first").length);
            D_dateBoxPanel.find("li.not-data:first").length<=0 && D_dateBoxPanel[0].scrollHeight>D_dateBoxPanel.height()?D_dateBoxScrollTool.show():D_dateBoxScrollTool.hide();
        }
    }

    function bindCopyEvent() {
        if(D_dateBox.find(".active").index()!=0)
        {
            return false;
        }
        //console.log("bindCopyEvent");
        //绑定复制密码按钮事件
        if (!fls.f || fls.v < 10) {
            D_myPage.find('.copy-readpwd:first').each(function () {
                $(this).show().qtip({
                    content: '不能自动复制，请使用“Ctrl+C”或者右键“复制”查阅密码到剪贴板',
                    position: {
                        at: 'top center',
                        my: 'bottom center'
                    },
                    show: {
                        event: 'click',
                        effect: false
                    },
                    hide: {
                        event: 'unfocus',
                        effect: false,
                        delay: 1000
                    }
                });
            });
        }
        else {
            var clipUrl = "clipboard";
            if (comm.lessThenIE(9) && comm.isIE()) {
                clipUrl = "clipboardLess";
            }
            require([clipUrl], function (ZeroClipboard) {
                /*D_myPage.find('.copy-readpwd').each(function () {
                    var tg = $(this);
                    var client = new ZeroClipboard(tg);
                    client.on('ready', function (readyEvent) {
                        client.on('aftercopy', function (event, args) {
                            tg.qtip({
                                style: {
                                    classes: "qtip-blue"
                                },
                                content: '复制成功',
                                position: {
                                    at: 'top center',
                                    my: 'bottom center'
                                },
                                show: {
                                    event: false,
                                    ready: true,
                                    effect: false
                                },
                                hide: {
                                    event: 'unfocus',
                                    effect: false
                                }
                            });
                        });
                    });
                });*/
                D_myPage.find('.copy-readpwd:first').each(function () {
                    var tg = $(this);
                    tg.show();
                    var client = new ZeroClipboard(tg);
                    client.on('ready', function (readyEvent) {
                        client.on('aftercopy', function (event, args) {
                            tg.qtip({
                                style: {
                                    classes: "qtip-blue"
                                },
                                content: '复制成功',
                                position: {
                                    at: 'top center',
                                    my: 'bottom center'
                                },
                                show: {
                                    event: false,
                                    ready: true,
                                    effect: false
                                },
                                hide: {
                                    event: 'unfocus',
                                    effect: false
                                }
                            });
                        });
                    });
                });

            });
        }
    }

    function loadMoreFile(start)
    {
        if(D_fileBox.attr("loaded") || D_fileBox.find("#file-box-loading").length>0)
        {
            return;
        }
        D_fileBox.find("ul").append("<li class='file-box-loading' id='file-box-loading'>正在加载更多...</li>");
        var params = {start:start};
        $.get("/trace/get_more_file",params,function(ret){
            if(ret.ret==-1)
            {
                var data = ret.data;
                if(data)
                {
                    renderFiles(data);
                }
                else
                {
                    D_fileBox.attr("loaded",true);
                    $("#file-box-loading").remove();
                    D_fileBox.find("ul").append("<li>没有更多了</li>");
                }
            }
            else
            {
                $("#file-box-loading").remove();
                SITE_TIP.setContent("数据加载失败!",true,false);
            }
        },"json");
    }

    //加载文件的相关信息
    function loadByFileId(file_id,clear)
    {
        var params = {file_id:file_id};
        //console.log($(".actor-filter.active").is(".my"));
        if($(".actor-filter.active").is(".my"))
        {
            params.my=true;
        }
        datesLoadingView();
        if(P_loadTraces)
        {
            P_loadTraces.abort();
        }
        P_loadTraces=$.get("/trace/get_by_file_id",params,function(ret){
            if(ret.ret==-1 && ret.data)
            {
                var data = ret.data;
                renderDates(data.dates,clear);
                if(data.traces)
                {
                    renderTraces(data.traces,clear);
                }
                else
                {
                    D_traceBoxCt.html("<div class='trace-empty'>没有相关的数据</div>");
                }
            }
            else
            {
                D_traceBoxCt.html("<div class='trace-empty'>没有相关的数据</div>");
                //D_dateBox.find("ul").html("");
                var ul = D_dateBox.find("ul");
                ul.html("");
                for(var a=0;a<5;a++)
                {
                    ul.append("<li class='not-data'></li>");
                }
                if(ret.ret!=-1)
                {
                    SITE_TIP.setContent("数据加载失败!",true,false);
                }
            }
        },"json");
    }

    //加载日期相关的信息

    function loadByDate(file_id,date,clear)
    {
        var params = {file_id:file_id,date:date};
        if($(".actor-filter.active").is(".my"))
        {
            params.my=true;
        }
        tracesLoadingView();
        if(P_loadTraces)
        {
            P_loadTraces.abort();
        }
        P_loadTraces=$.get("/trace/get_by_date",params,function(ret){
            if(ret.ret==-1 && ret.data)
            {
                var data = ret.data;
                renderTraces(data,clear);
            }
            else
            {
                D_traceBoxCt.html("<div class='trace-empty'>没有相关的数据</div>");
                //SITE_TIP.setContent("数据加载失败!",true,false);
            }
        },"json");
    }

    /**
     * 渲染文件
     * @param data
     * @param prepend
     * @param active
     * @returns {boolean}
     */
    function renderFiles(data,prepend,active)
    {
        prepend = prepend || false;
        $("#file-box-loading").remove();
        var ul = D_fileBox.find("ul");
        if(!data)
        {
            return false;
        }
        var template = $('#fileTpl').html();
        var d = Mustache.render(template,{files:data});
        prepend?ul.prepend(d):ul.append(d);
        if(active)
        {
            var active_id = data[data.length-1]['id'];
            D_fileBox.find("[data-uuid='"+active_id+"']").trigger("click");
        }
        //调整日期列表界面
        adjustFileBox();
    }
    function datesLoadingView()
    {
        var ul = D_dateBox.find("ul");
        var len = parseInt(ul.find("li").length)||0;
        ul.html("");
        for(var a=0;a<len;a++)
        {
            if(a==0)
            {
                ul.append("<li class='not-data'>正在加载...</li>");
            }
            else
            {
                ul.append("<li class='not-data'></li>");
            }
        }


        tracesLoadingView();
    }
    //渲染日期列表
    function renderDates(data,clear)
    {
        var ul = D_dateBox.find("ul");
        //ul.hide();
        clear  = clear || false;
        if(clear){
            ul.html("");
            D_traceBoxCt.html("");
        }
        if(!data)
        {
            return false;
        }
        var template = $('#dateTpl').html();
        var d = Mustache.render(template,{dates:data});
        ul.append(d);
       // console.log("%s %s",C_dateBoxMinLen,data.length);
        var len = C_dateBoxMinLen-data.length;
        if(len>0)
        {
            for(var a=0;a<len;a++)
            {
                ul.append("<li class='not-data'></li>");
            }
        }
        ul.fadeIn("fast");
        //调整日期列表界面
        adjustDateBox();
    }
    function tracesLoadingView()
    {
        D_traceBoxCt.html("<div class='trace-loading'>正在加载...</div>");
    }
    //渲染文件轨迹内容页
    function renderTraces(data,clear)
    {
        D_myPage.scrollTop(0);
        D_myPage.hide();
        clear  = clear || false;
        if(clear){
            D_traceBoxCt.html("");
        }
        if(!data)
        {
            return false;
        }
        var template = $('#traceTpl').html();
        var d = Mustache.render(template,{traces:data[0].list});
        D_traceBoxCt.html(d);
        D_myPage.fadeIn("fast");
        bindCopyEvent();
    }

    //列表选中后添加焦点样式
    function active(box,item,dom)
    {
        dom  = dom || "li";
        box.find(dom+".active").removeClass("active");
        item.addClass("active");
    }

    //初始化
    function init(){
        //自动调整界面
        autoAdjustView();
        $(window).resize(function(){
            autoAdjustView();
        });
        if(D_traceWrap.is(":hidden"))
        {
            return;
        }
        //D_traceList.show();
        //显示文件列表

        //文件列表点击事件
        D_fileBox.delegate("li","click",function(){
            var m = $(this);
            var id =  m.attr("data-uuid");
            //如果其他列表没加载完不能加载
            /*if($(".trace-loading").length>0)
            {
                return;
            }*/
            if(!m.is(".active") && id)
            {
                active(D_fileBox,m);
                loadByFileId(id,true);
            }
        });
        D_fileBox.listHelper();
        var A_scrollOffset = D_fileBox.find("li:first").height()*3;
        //文件列表的向上滚动按钮
        D_fileBox.find(".page-wrap .icon-up").bind("click",function(){
            D_fileBoxPanel.stop(true).animate({scrollTop:D_fileBoxPanel.scrollTop()-A_scrollOffset}, 500);
            return false;
        });
        var A_file_rows = parseInt(D_fileBox.attr("data-rows"));
        //文件列表的向下滚动按钮
        D_fileBox.find(".page-wrap .icon-down").bind({
            "click":function()
            {
                if(!D_fileBox.attr("loaded"))
                {
                    if(D_fileBoxPanel[0].scrollHeight-D_fileBoxPanel.scrollTop()-D_fileBoxPanel.height()<=A_scrollOffset*2)
                    {
                        var start = parseInt(D_fileBox.find("li:last").index());
                        if(start>=(A_file_rows-1))
                        {
                            loadMoreFile(start+1);
                        }
                    }
                }
                D_fileBoxPanel.stop(true).animate({scrollTop:D_fileBoxPanel.scrollTop()+A_scrollOffset}, 500);
                return false;
            }
        });


        //日期列表点击事件
        D_dateBox.delegate("li","click",function(){
            var m = $(this);
            var date =  m.attr("data-uuid");
            var file_id = D_fileBox.find("li.active").attr("data-uuid");
            if(!m.is(".active") && date)
            {
                active(D_dateBox,m);
                loadByDate(file_id,date,true);
            }
        });

        var A_dateScrollOffset = D_dateBox.find("li:first").height()*3;
        //文件列表的向上滚动按钮
        D_dateBox.find(".page-wrap .icon-up").bind("click",function(){
            D_dateBoxPanel.stop(true).animate({scrollTop:D_dateBoxPanel.scrollTop()-A_dateScrollOffset}, 500);
            return false;
        });
        //文件列表的向下滚动按钮
        D_dateBox.find(".page-wrap .icon-down").bind({
            "click":function(){
                D_dateBoxPanel.stop(true).animate({scrollTop:D_dateBoxPanel.scrollTop()+A_dateScrollOffset}, 500);
                return false;
            }
        });
        //复制按钮事件绑定
        bindCopyEvent();



        $(".actor-filter").click(function(){
            var m = $(this);
            $(".actor-filter.active").removeClass("active");
            m.addClass("active");
            var file_id = D_fileBox.find("li.active").attr("data-uuid");
            var date = D_dateBox.find("li.active").attr("data-uuid");
            if(!date)
            {
                loadByFileId(file_id,true);
            }
            else
            {
                loadByDate(file_id,date,true);
            }
        });
    }

    var trace = function()
    {
        init();
    };

    function resetView()
    {
        D_traceWrap.show();
        $("#empty-box").remove();
        init();
    }

    trace.prototype.prependFile = function(file)
    {
        var reset = D_traceWrap.is(":hidden");
        if(reset)
        {
            resetView();
        }
        file.uuid = file.id;
        renderFiles([file],true,reset);
    };
    return trace;
});